package org.chen.scene.service.geocode;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.scene.dto.BaiduGeocodingResponse;
import org.chen.common.scene.entity.CityCoordinate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;

@Slf4j
@Service
public class GeocodingService {
    
    @Autowired
    private CityCoordinateService cityCoordinateService;
    
    @Autowired
    private BaiduGeocodingApiService baiduGeocodingApiService;
    
    /**
     * 根据城市名称获取经纬度
     * 优先从数据库查询，查询不到则调用百度API并存储结果
     */
    public CityCoordinateResult getCityCoordinates(String cityName) {
        if (!StringUtils.hasText(cityName)) {
            return null;
        }
        
        log.info("查询城市坐标: {}", cityName);
        
        // 1. 首先从数据库查询
        String normalizedName = normalizeCityName(cityName);
        CityCoordinate dbResult = cityCoordinateService.getBaseMapper()
            .findByCityName(cityName, normalizedName);
        
        if (dbResult != null) {
            log.info("从数据库找到城市 {} 的坐标: [{}, {}]", 
                cityName, dbResult.getLatitude(), dbResult.getLongitude());
            return new CityCoordinateResult(dbResult.getLatitude(), dbResult.getLongitude(), "database");
        }
        
        // 2. 数据库没有找到，调用百度API
        log.info("数据库未找到城市 {}，尝试调用百度API", cityName);
        BaiduGeocodingResponse.Result.Location baiduLocation = 
            baiduGeocodingApiService.getCityCoordinatesFromBaidu(cityName);
        
        if (baiduLocation != null) {
            // 3. 保存到数据库
            CityCoordinate newCoordinate = new CityCoordinate();
            newCoordinate.setCityName(cityName);
            newCoordinate.setNormalizedName(normalizedName);
            newCoordinate.setLatitude(baiduLocation.getLat());
            newCoordinate.setLongitude(baiduLocation.getLng());
            newCoordinate.setSource("baidu_api");
            newCoordinate.setEnabled(true);
            
            try {
                cityCoordinateService.save(newCoordinate);
                log.info("成功保存城市 {} 的坐标到数据库", cityName);
            } catch (Exception e) {
                log.error("保存城市坐标到数据库失败: {}", cityName, e);
            }
            
            return new CityCoordinateResult(baiduLocation.getLat(), baiduLocation.getLng(), "baidu_api");
        }
        
        log.warn("未能找到城市 {} 的坐标信息", cityName);
        return null;
    }
    
    /**
     * 标准化城市名称
     */
    private String normalizeCityName(String cityName) {
        if (!StringUtils.hasText(cityName)) {
            return cityName;
        }
        
        String normalized = cityName.trim();
        if (normalized.endsWith("市")) {
            normalized = normalized.substring(0, normalized.length() - 1);
        }
        if (normalized.endsWith("区")) {
            normalized = normalized.substring(0, normalized.length() - 1);
        }
        if (normalized.endsWith("县")) {
            normalized = normalized.substring(0, normalized.length() - 1);
        }
        return normalized;
    }
    
    /**
     * 验证坐标是否有效
     */
    public boolean isValidCoordinates(BigDecimal latitude, BigDecimal longitude) {
        if (latitude == null || longitude == null) {
            return false;
        }
        
        return latitude.compareTo(new BigDecimal("-90")) >= 0 && 
               latitude.compareTo(new BigDecimal("90")) <= 0 &&
               longitude.compareTo(new BigDecimal("-180")) >= 0 && 
               longitude.compareTo(new BigDecimal("180")) <= 0;
    }
    
    /**
     * 坐标结果包装类
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class CityCoordinateResult {
        private BigDecimal latitude;
        private BigDecimal longitude;
        private String source; // 数据来源：database 或 baidu_api
    }
}